
import "dart:ffi";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/bill/widgets/show_multi_date_picker.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/widgets/info_block.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/widgets/info_item.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

enum DueInAddType {
  single,
  multiple,
}
class TabPane extends StatefulWidget {
  final DueInAddType type;
  final List list;
  final Function onChange;
  final double totalMoney;
  final Function onRemove;
  final int roomId;
  final int checkInId;
  const TabPane({super.key, required this.type, required this.list, required this.onChange, required this.totalMoney, required this.onRemove, required this.roomId, required this.checkInId});

  @override
  State<StatefulWidget> createState() => _TabPaneState();

}

class _TabPaneState extends State<TabPane> with AutomaticKeepAliveClientMixin{

  final Widget _requiredTip = const Text("*", style: TextStyle(color: ThemeVars.colorError),);
  Map<String, dynamic> _params = {
    "name": "",
    "billCycleBegin": DateTools.formatYMD(DateTime.now()),
    "billCycleEnd": DateTools.formatYMD(DateTime.now().add(Duration(days: 365))),
    "money": "",
    "noticeDate": DateTools.formatYMD(DateTime.now()),
    "inoutFlag": "1",
    "belong": "1",
    "payPlatForm": "1",
    "status": "1",
    "checkInId": "",
    "roomId": "",
  };
  int _collectType = 1;
  int _day = 1;
  List _list = [];


  void _createMultipleBill() {
    DateTime startDate = DateTime.parse(_params["billCycleBegin"]);
    DateTime endDate = DateTime.parse(_params["billCycleEnd"]);
    print("startDate: ${DateTime.parse(_params["billCycleBegin"])}, endDate: ${DateTime.parse(_params["billCycleEnd"])}");
    int month = (((endDate.year - startDate.year) * 12 + endDate.month - startDate.month) / _collectType).ceil();
    List list = List.generate(month, (index) {
      DateTime start = DateTools.add(startDate, type: AddType.month, num: _collectType * index).add(const Duration(days: 1));
      DateTime end = DateTools.add(startDate, type: AddType.month, num: _collectType * index + _collectType);
      if (index == month - 1) {
        end = endDate;
      }
      DateTime noticeDate;
      if (index == 0) {
        noticeDate = DateTime.now();
      } else {
        DateTime notice = DateTools.add(DateTime(startDate.year, startDate.month - 1, _day), type: AddType.month, num: _collectType * index).add(const Duration(days: 1));
        noticeDate = notice.isBefore(DateTime.now()) ? DateTime.now() : notice;
      }
      String money = (double.parse(_params["money"]) * _collectType).toStringAsFixed(2);

      return {
        "billCycleBegin": DateTools.formatYMD(start),
        "billCycleEnd": DateTools.formatYMD(end),
        "noticeDate": DateTools.formatYMD(noticeDate),
        "money": money,
        "name": "${_params["name"]}(${index + 1}/$month)",
        "inoutFlag": "1",
        "belong": "1",
        "payPlatForm": "1",
        "status": "1",
        "checkInId": widget.checkInId,
        "roomId": widget.roomId,
      };
    });
    print(list);
    setState(() {
      // _list = list;
      widget.onChange(list);
    });
  }

  void _createSingleBill() {

    widget.onChange([{
      "billCycleBegin": DateTools.formatYMD(_params["billCycleBegin"]),
      "billCycleEnd": DateTools.formatYMD(_params["billCycleEnd"]),
      "noticeDate": DateTools.formatYMD(_params["noticeDate"]),
      "money": _params["money"],
      "name": _params["name"],
      "inoutFlag": "1",
      "belong": "1",
      "payPlatForm": "1",
      "status": "1",
      "checkInId": widget.checkInId,
      "roomId": widget.roomId,
    }]);
  }

  void _selectCollectTypeModalPopup({Function? onConfirm, int? collectType, int? collectDay}) async {
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          int type = collectType ?? 1;
          List collectTypeList = [
            {"label": "每1月", "value": 1},
            {"label": "每2月", "value": 2},
            {"label": "每3月", "value": 3},
            {"label": "每4月", "value": 4},
            {"label": "每6月", "value": 6},
            {"label": "每12月", "value": 12},
          ];
          int day = collectDay ?? 1;
          List days = List.generate(31, (index) => index + 1);
          List list = [];

          print("day: $day, type: $type, ${collectTypeList.indexWhere((item) => item["value"] == type)}");

          return Container(
              height: 246,
              padding: const EdgeInsets.only(top: 6.0),
              margin: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              color: CupertinoColors.systemBackground.resolveFrom(context),
              child: SafeArea(
                  top: false,
                  child: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                              onTap:() {
                                Navigator.pop(context);
                              },
                              child: const Text("取消"),
                            ),
                            GestureDetector(
                              onTap:() {
                                if (onConfirm != null) onConfirm(type, day);
                                Navigator.pop(context);
                              },
                              child: const Text("确定", style: TextStyle(color: ThemeVars.colorPrimary),),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 216,
                        child: Row(
                          // mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Expanded(
                              child: CupertinoPicker(
                                itemExtent: 36,
                                scrollController: FixedExtentScrollController(initialItem: collectTypeList.indexWhere((item) => item["value"] == type)),
                                onSelectedItemChanged: (int value) => setState(() {
                                  print("改变了${collectTypeList[value]["value"]}");
                                  type = collectTypeList[value]["value"];
                                }),
                                children: collectTypeList.map((ele) {
                                  String text = ele["label"];
                                  return Center(
                                    child: Text(text, style: const TextStyle(fontSize: 16)),
                                  );
                                }).toList(),
                              ),
                            ),
                            Expanded(
                                child: CupertinoPicker(
                                  itemExtent: 36,
                                  scrollController: FixedExtentScrollController(initialItem: days.indexWhere((item) => item == day)),
                                  onSelectedItemChanged: (int value) => day = value + 1,
                                  children: days.map((ele) {
                                    String text = "$ele号";
                                    return Center(
                                      child: Text(text, style: const TextStyle(fontSize: 16)),
                                    );
                                  }).toList(),
                                )
                            ),
                          ],
                        ),
                      )
                    ],
                  )
              )
          );
        }
    );
  }

  bool _validateCreateBill() {
    if (_params["name"].isEmpty) {
      EasyLoading.showToast("请填写完整信息");
      return false;
    }
    if (_params["money"] is String && _params["money"].isEmpty) {
      EasyLoading.showToast("请填写完整信息");
      return false;
    }
    return true;
  }
  
  void _batchAddBill() async {
    EasyLoading.show();
    await billApi.batchAdd(_list);
    EasyLoading.showToast("添加成功");
    Stacker.pop(true);
  }

  @override
  void initState() {
    super.initState();
    switch(widget.type) {
      case DueInAddType.single:
        _params = {
          "name": "",
          "billCycleBegin": DateTools.formatYMD(DateTime.now()),
          "billCycleEnd": DateTools.formatYMD(DateTime.now().add(Duration(days: 365))),
          "money": "",
          "noticeDate": DateTools.formatYMD(DateTime.now()),
          "inoutFlag": "1",
          "belong": "1",
          "payPlatForm": "1",
          "status": "1",
          "checkInId": widget.checkInId,
          "roomId": widget.roomId,
        };
        break;
      case DueInAddType.multiple:
        _params = {
          "name": "",
          "billCycleBegin": DateTools.formatYMD(DateTime.now()),
          "billCycleEnd": DateTools.formatYMD(DateTime.now().add(Duration(days: 365))),
          "money": "",
          "noticeDate": DateTools.formatYMD(DateTime.now()),
          "collectType": "", // 收款周期
          "collectDay": "", // 收款日
          "inoutFlag": "1",
          "belong": "1",
          "payPlatForm": "1",
          "status": "1",
          "checkInId": widget.checkInId,
          "roomId": widget.roomId,
        };
        break;
    }
    setState(() {
      _list = widget.list;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(
      children: [
        ListView(
          padding: EdgeInsets.only(bottom: 64),
          children: [
            MenuBlock(
              items: [
                MenuBlockItem(
                    text: "费用名称",
                    prefix: _requiredTip,
                    suffix: TextFormField(

                      decoration: const InputDecoration(
                        hintText: "请输入",
                        border: InputBorder.none,
                        hintStyle: TextStyle(fontSize: 14),
                        isDense: true,
                      ),
                      initialValue: _params["name"],
                      textAlign: TextAlign.right,
                      onChanged: (value) => setState(() {
                        _params["name"] = value;
                      }),
                    )
                ),
                MenuBlockItem(
                    text: "金额",
                    prefix: _requiredTip,
                    suffix: TextFormField(
                      keyboardType: TextInputType.number,
                      decoration: const InputDecoration(
                        hintText: "请输入",
                        border: InputBorder.none,
                        hintStyle: TextStyle(fontSize: 14),
                        isDense: true,
                      ),
                      initialValue: _params["money"],
                      textAlign: TextAlign.right,
                      onChanged: (value) => setState(() {
                        _params["money"] = value;
                      }),
                    )
                ),
                MenuBlockItem(
                    text: "账单周期",
                    prefix: _requiredTip,
                    suffix: Text("${_params["billCycleBegin"]} - ${_params["billCycleEnd"]}"),
                    onTap: () {
                      showMultiDatePicker(
                          context: context,
                          type: DateTimeType.range,
                          startDate: DateTime.parse(_params["billCycleBegin"]),
                          endDate: DateTime.parse(_params["billCycleEnd"]),
                          onchange: (dateRange) {
                            setState(() {
                              _params["billCycleBegin"] = dateRange[0];
                              _params["billCycleEnd"] = dateRange[1];
                            });
                          }
                      );
                    }
                ),
                if (widget.type == DueInAddType.single) MenuBlockItem(
                    text: "待收日期",
                    prefix: _requiredTip,
                    suffix: Text(_params["noticeDate"]),
                    onTap: () {
                      showDatetimePicker(
                          context: context,
                          initialDateTime: DateTime.parse(_params["noticeDate"]),
                          onchange: (date) {
                            setState(() {
                              _params["noticeDate"] = DateTools.formatYMD(date);
                            });
                          }
                      );
                    }
                ),
                if (widget.type == DueInAddType.multiple) MenuBlockItem(
                    text: "付款方式",
                    prefix: _requiredTip,
                    suffix: Text("每$_collectType月$_day号"),
                    onTap: () {
                      _selectCollectTypeModalPopup(collectType: _collectType, collectDay: _day, onConfirm: (collectType, day) {
                        setState(() {
                          _collectType = collectType;
                          _day = day;
                        });

                      });
                    }
                ),
              ],
            ),
            const SizedBox(height: 12,),
            MenuBlock(
              items: [],
              content: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if (_validateCreateBill()) {
                    widget.type == DueInAddType.multiple ? _createMultipleBill() : _createSingleBill();
                  }
                },
                child: Container(
                  child: const Text("生成待收账单", textAlign: TextAlign.center, style: TextStyle(color: ThemeVars.colorPrimary),),
                ),
              ),
            ),
            const SizedBox(height: 12,),
            if (_list.isNotEmpty) Container(
              padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
              child: Column(
                children: List.generate(_list.length * 2 - 1, (index) {
                  if (index.isOdd) {
                    return const SizedBox(height: 12,);
                  }
                  Map item = _list[index ~/ 2];
                  return SizedBox(
                    width: MediaQuery.of(context).size.width,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              widget.onRemove(index ~/ 2);
                            });
                          },
                          child: const Icon(Icons.remove_circle_outline, color: ThemeVars.colorError, size: 20,),
                        ),
                        const SizedBox(width: ThemeVars.paddingPage,),
                        Expanded(
                          child: InfoBlock(
                            title: item["name"],
                            actions: [Text("${item["money"]}元")],
                            borderRadius: BorderRadius.circular(8),
                            children: [
                              InfoItem(
                                label: "账单周期",
                                value: "",
                                customValue: Row(
                                  children: [
                                    GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      onTap: () {},
                                      child: Text("${item["billCycleBegin"]} 至 "),
                                    ),
                                    GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      onTap: () {},
                                      child: Text("${item["billCycleEnd"]}"),
                                    ),
                                  ],
                                ),
                              ),
                              InfoItem(
                                label: "待收日期",
                                value: "",
                                customValue: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {},
                                  child: Text("${item["noticeDate"]}"),
                                ),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  );
                }),
              ),
            ),
          ],
        ),
        if (_list.isNotEmpty) Positioned(
          left: 0,
          bottom: 0,
          width: MediaQuery.of(context).size.width,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text("待收：", style: TextStyle(fontSize: 12),),
                    Text(Utils.formatCurrency(widget.totalMoney), style: TextStyle(color: ThemeVars.colorError, fontSize: 14),),
                  ],
                ),
                Button(
                  onPressed: () {
                    _batchAddBill();
                  },
                  child: Text("保存"),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

}